package cc.vv.party.service.impl;

import cc.vv.party.beans.model.Team;
import cc.vv.party.beans.model.UserRole
import cc.vv.party.beans.vo.SignInVO
import cc.vv.party.beans.vo.TeamVO
import cc.vv.party.mapper.TeamMapper;
import cc.vv.party.service.TeamService;
import cc.vv.party.common.base.BaseServiceImpl;
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.ext.uuid
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.RoleMapper
import cc.vv.party.mapper.TeamSignInMapper
import cc.vv.party.mapper.UserRoleMapper
import cc.vv.party.param.TeamEditParam
import com.baomidou.mybatisplus.mapper.EntityWrapper
import com.baomidou.mybatisplus.plugins.Page
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import org.apache.commons.collections.CollectionUtils
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.Validate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional

/**
 * <p>
 * 四支队伍信息 服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class TeamServiceImpl : BaseServiceImpl<TeamMapper, Team>(), TeamService {

    @Autowired
    lateinit var teamSignInMapper: TeamSignInMapper

    @Autowired
    lateinit var roleMapper: RoleMapper

    @Autowired
    lateinit var userRoleMapper: UserRoleMapper


    override fun getSecretaryMessage(village: String): TeamVO {
        var paramTeam = Team()
        paramTeam.village = village
        paramTeam.teamType = "0"
        var resultTeam = baseMapper.selectOne(paramTeam) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST.statusCode, "队伍信息不存在")
        return resultTeam.transfer()
    }

    override fun findVillageTeamList(village: String, type: String): List<TeamVO>? {
        var teamList = super.selectList(EntityWrapper<Team>().where("village = {0}", village).and("team_type = {0}", type))
        if(CollectionUtils.isNotEmpty(teamList)){
            return teamList!!.transferEntries<TeamVO>() as ArrayList
        }
        return emptyList()
    }

    @Transactional(rollbackFor = [(Exception::class)])
    override fun edit(param: TeamEditParam, userId: String): Boolean {

        var entity: Team

        var role = roleMapper.getByType("team")

        if(StringUtils.isBlank(param.id)){
            entity = param.transfer<Team>()
            entity.id = uuid()
            entity.createUser = userId
            super.insert(entity)

        } else {
            entity = super.selectById(param.id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
            if(StringUtils.isNotBlank(param.pname)) entity.pname = param.pname
            if(StringUtils.isNotBlank(param.faceUrl)) entity.faceUrl = param.faceUrl
            if(param.sex != null) entity.sex = param.sex
            if(param.age != null) entity.age = param.age
            if(StringUtils.isNotBlank(param.education)) entity.education = param.education
            if(StringUtils.isNotBlank(param.town)) entity.town = param.town
            if(StringUtils.isNotBlank(param.mobile)) entity.mobile = param.mobile
            if(StringUtils.isNotBlank(param.village)) entity.village = param.village
            if(StringUtils.isNotBlank(param.teamType)) entity.teamType = param.teamType
            if(StringUtils.isNotBlank(param.plant)) entity.plant = param.plant

            super.updateById(entity)

            val count = userRoleMapper.selectCount(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", entity.mobile))
            if(count <= 0){
                userRoleMapper.delete(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", entity.mobile))
            } else {
                return true
            }
        }

        //添加管理员权限
        var admin = UserRole()
        admin.roleId = role.id
        admin.userAccount = entity.mobile
        admin.createUser = userId
        userRoleMapper.insert(admin)

        return true
    }

    override fun deleteTeam(id: String): Boolean {
        var entity = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)

        var role = roleMapper.getByType("team")

        userRoleMapper.delete(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", listOf(entity.mobile)))

        return super.deleteById(id)
    }

    override fun info(id: String): TeamVO {
        var entity = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
        return entity.transfer()
    }

    override fun villageTeamList(village: String): List<TeamVO> {
        var list = super.selectList(EntityWrapper<Team>().where("village = {0}", village)) ?: emptyList()
        return list.transferEntries<TeamVO>() as ArrayList
    }

    override fun listPage(town: String?, village: String?, teamType: String?, size: Int, page: Int): PageWrapper<TeamVO> {
        var pages = Page<TeamVO>(page, size)
        pages.records = baseMapper.selectListPage(pages, town, village, teamType)
        return pages.transfer()
    }



}
